<template>
	<div>
		<div ref="biaotou">
			<el-form inline :model="formData">
				<el-row>
					<el-col :span="24"> 
						<el-form-item label="单据状态:">
							<el-select v-model="formData.status" clearable>
								<el-option :value="0" label="待审核"></el-option>
								<el-option :value="1" label="审批完成"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="工单编号:">
							<el-input v-model="formData.payrollFormNumber"></el-input>
						</el-form-item>
						<el-form-item label="开始时间:">
							<el-date-picker v-model="formData.createTime" type="month" value-format="yyyy-MM-dd"></el-date-picker>
						</el-form-item>
						<el-form-item label="结束时间:">
							<el-date-picker v-model="formData.endTime" type="month" value-format="yyyy-MM-30"></el-date-picker>
						</el-form-item>
						<el-form-item label="施工类别:">
							<el-select v-model="formData.constructionType" style="width: 100%;" clearable filterable>
								<el-option v-for="(item,index) in constructionType" :value="item.Value"
									:label="item.Description"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="负责人:">
							<el-select v-model="formData.personId" style="width: 100%;" clearable filterable>
								<el-option v-for="(item,index) in $store.state.AllUsers" :value="item.Id" v-show="item.Id!=1"
									:label="item.UserName"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="工单人员:">	
							<el-select v-model="formData.orderUserId" clearable filterable>
								<el-option v-for="(item,index) in $store.state.AllUsers" :value="item.Id" v-show="item.Id!=1"
									:label="item.UserName"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="年份"  v-if="$store.state.user.roleid == '1'">
							<el-date-picker type="year" v-model="formData.settlementNumber" value-format="yyyy"  filterable clearable></el-date-picker>
						</el-form-item>
						<el-form-item label="">
							<el-checkbox style="width:100%" v-model="formData.IsDelete" label="已删除单据" border></el-checkbox>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="getTableData">查询</el-button>
						</el-form-item>
						<el-form-item>
							<el-button type="success" @click="PayrollDetailsAddEntiy.show = true"
							:disabled="project.ProjectStatus == 1">新建收方单</el-button>
						</el-form-item>
					</el-col>
				</el-row>
				<!-- <el-row>
					<el-col :span="24">
						<el-button type="success" @click="PayrollDetailsAddEntiy.show = true"
							:disabled="project.ProjectStatus == 1">新建</el-button>
						<el-tooltip class="item" effect="dark" content="年度开账将结算上一年度数据" placement="right">
							<el-button type="primary" icon="el-icon-s-check"
								@click="UpSettlementDialog">年度开账</el-button>
						</el-tooltip>
						</el-form-item>
					</el-col>
				</el-row> -->
			</el-form>
		</div>
		<div ref="zhenwen">
			<el-table v-loading="pagination.tableloading" :height="tableStyle+'px'" ref="eltableMain" :data="payrollList" border show-summary :summary-method="getSummaries" @select="tableSelectEvent" @select-all="tableSelectEvent">
				<el-table-column type="selection" width="40" align="center"></el-table-column>
				<el-table-column type="index" label="序号" width="50" align="center"
					:index="indexMethod"></el-table-column>
				<el-table-column label="工单编号" align="center" prop="PayrollNumber" width="80"></el-table-column>
				<el-table-column label="施工类别" align="center" prop="ConstructionType">
					<template slot-scope="scope">
						{{ getDataMessage('Category',scope.row) }}
					</template>
				</el-table-column>						   
				<el-table-column label="施工部位" align="center" prop="ConstructionPart" width="300"></el-table-column>
				<el-table-column label="工作内容" align="center" prop="JobContent" width="350"></el-table-column>
				<el-table-column label="开始时间" align="center" prop="CreateTime">
					<template slot-scope="scope">
						{{ shijianzhuanhua(scope.row.CreateTime) }}
					</template>
				</el-table-column>
				<el-table-column label="方量(平方数量)" align="center" prop="Squarequantity"></el-table-column>
				<el-table-column label="单价" align="center" prop="Price"></el-table-column>
				<el-table-column label="总价" align="center" prop="Totalprice"></el-table-column>
				<el-table-column label="责任人" align="center" prop="PersonId">
					<template slot-scope="scope">
						{{ getDataMessage('User',scope.row) }}
					</template>
				</el-table-column>
				<el-table-column label="工单人员">
					<template slot-scope="scope">
						<el-popover placement="right" width="400" trigger="hover" @show="getPayrollUserAsync(scope.row.Id)">
							<el-table :data="workPersons" stripe>
								<el-table-column prop="Id" label="姓名" align="center">
									<template slot-scope="scope">
										{{ getUserInfo(scope.row,'UserName') }}
									</template>
								</el-table-column>
								<el-table-column prop="WorkingDays" label="工天" align="center"></el-table-column>
								<el-table-column prop="Price" label="单价" align="center"></el-table-column>
								<el-table-column prop="TotalPrice" label="总计" align="center"></el-table-column>
							</el-table>
							<el-button type="text" slot="reference">人员明细</el-button>							
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column label="备注" align="center" prop="Remark"></el-table-column>
				<el-table-column label="审批状态" align="center" prop="PayrollType">
					<template slot-scope="scope">
						<p v-if="scope.row.PayrollType == 0" style="color: #E6A23C;">待审批</p>
						<p v-else style="color: #67C23A;">审批完成</p>
					</template>
				</el-table-column>
				<el-table-column label="开账状态" align="center" prop="FinanceReimbursementStart">
					<template slot-scope="scope">
						<p v-if="scope.row.Settlement" style="color: #67C23A;">({{ scope.row.SettlementNumber }}开账 账单)</p>
						<p v-else style="color: #e6a23c;">({{ scope.row.SettlementNumber }}年度 账单)</p>
					</template>
				</el-table-column>
				<el-table-column label="附件" align="center" prop="Remark">
					<template slot-scope="scope">
						<el-button type="text" @click="DownLoadFileEvent(scope.row)">下载</el-button>
					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" header-align="center"  align="center" width="300">
					<template slot-scope="scope">
						<el-button plain type="primary" size="mini" @click="getPayrollDetails(scope.row)" style="margin-left: 10px;">详情</el-button>
						<el-button plain type="primary" size="mini" @click="OpenSettlementDialog(scope.row)" >年度开账</el-button>
						<br>
						<div style="margin-top:10px">
							<el-popover placement="right" width="400" trigger="click" style="margin-right: 10px;">
								<UploadFileF ref="AnotherData" :multiple="true" :another-data="AnotherData"
									:showfilelist="true" :upshow="true" content="上传文件" btnsize="medium"></UploadFileF>
								<el-button plain type="primary" slot="reference" size="mini"
									@click="AnotherData.id = scope.row.Id">附件上传</el-button>
							</el-popover>
							<el-button plain type="info" size="mini" @click="GetPayrollFormExcel(scope.row)">导出</el-button>
							<el-popconfirm title="这是一段内容确定删除吗" @confirm="deletePayrollDetails(scope.row)"
								style="padding-left: 10px;">
								<el-button slot="reference" plain type="danger" size="mini"
									:disabled="project.ProjectStatus == 1">删除</el-button>
							</el-popconfirm>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<el-row>
				<el-col :span="24" align="right">
					<el-pagination @size-change="getTableData" @current-change="getTableData"
						:current-page.sync="pagination.currentPage" :page-sizes="pagination.pagesizes"
						:page-size.sync="pagination.pagesize" layout="total, sizes, prev, pager, next, jumper"
						:total.sync="pagination.total">
					</el-pagination>
				</el-col>
			</el-row>
		</div>

		<el-dialog :visible.sync="PayrollDetailsEntiy.show" title="工单详情" width="90%" :append-to-body='true'
			@close="getTableData()">
			<payrollForm :project="project" :jobContentList="payrollFormConstructionType"
				:payrollEntity="PayrollDetailsEntiy.PayrollDetails" :closeFun="childrenCloseEvent"></payrollForm>
		</el-dialog>

		<el-dialog :visible.sync="PayrollDetailsAddEntiy.show" title="新建收方工资单" width="90%" :append-to-body='true'
			@close="payrollFormAddRefEvent()">
			<payrollFormAdd ref="payrollFormAddRef" :project="project" :closeFun="childrenCloseEvent"
				:jobContentList="payrollFormConstructionType"></payrollFormAdd>
		</el-dialog>

		<el-dialog append-to-body title="提示" :visible.sync="kaizhangDialog.show" width="30%"
			@close="dialogVisibleEvent">
			<div style="display: flex;flex-direction: column;gap: 10px;">
				<span>你确定要开账此选择吗?</span>
				<div>
					开帐年份：<el-date-picker v-model="kaizhangDialog.SettlementNumber" type="year" value-format="yyyy"
						placeholder="选择年份" @change="SettlementNumberEvent"></el-date-picker>
				</div>
				<div v-if="CheckSettlementResult.StatusCode == 500 && CheckSettlementResult.Message!=''">
					<p style="color: #E6A23C;margin:5px 0px !important; ">{{ CheckSettlementResult.Message }}</p>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisibleEvent">取 消</el-button>
				<el-button type="primary" @click="IsUpSettlementHandlerNew(false)">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		Message,
		Switch
	} from 'element-ui'
	import payrollForm from './payrollForm.vue'
	import payrollFormAdd from './payrollFormAdd.vue'
	import * as publicjs from "../../../../public/Scriput/Public"
	import UploadFileF from "../../UploadFileF";
	import * as dayjs from 'dayjs'
	
	var utc = require('dayjs/plugin/utc')
	dayjs.extend(utc)
	
	export default {
		name: 'payrollList',
		components: {
			payrollForm,
			payrollFormAdd,
			UploadFileF
		},
		props: {
			project: {
				type: Object,
				required: true
			}
		},
		data() {
			return {
				payrollList: [],
				fuzerenList: [{
						name: '1111',
						value: 1
					},
					{
						name: '22222',
						value: 2
					},
				],
				formData: {
					status:0,
					//createTime: dayjs().add('-3','month').format("YYYY-MM-01"),
					//endTime: dayjs().format("YYYY-MM-01"),
					createTime: '',
					endTime: '',
					constructionType:'',
					personId:'',
					orderUserId:'',
					payrollFormNumber:'',
					settlementNumber:'',
					IsDelete: false,
				},
				//分页数据绑定
				pagination: {
					currentPage: 1,
					pagesizes: [10, 50, 100, 300, 500],
					pagesize: 10,
					total: 0,
					tableloading: false
				},
				PayrollDetailsEntiy: {
					PayrollDetails: {},
					show: false,
				},
				PayrollDetailsAddEntiy: {
					show: false,
				},
				deleteVisible: false,
				constructionPart: [],
				constructionType: [],
				payrollFormConstructionType: [],
				AnotherData: {
					//项目模块
					FileType: 256,
					//项目Id号
					id: 0,
					//Type：1：收方工资单 2、应发工资单、3报销单 
					Type: 1,
					Single: false,
				},
				tableSelectRows: [],
				kaizhangDialog: {
					show: false,
					SettlementNumber: '',
					clickrow:[],
				},
				CheckSettlementResult: {
					Status: true,
					Message: '',
					StatusCode: 200
				},
				//工单人员
				workPersons:[],
				tableStyle:500,
			}
		},
		created() {
			publicjs.http(this.$http, this.$message)
		},
		mounted() {
			this.getConstructionPartEnum()
			this.getConstructionType()
			this.getPayrollFormConstructionType()
			this.$nextTick(() => {
				let _this = this
				this.getTableData()
			})
			window.addEventListener('resize', ()=>{
				this.tableHeightJiSuan()
			})
		},
		updated() {
			this.$nextTick(()=>{
				this.$refs.eltableMain.doLayout()
			})
		},
		methods: {
			//表格序号
			indexMethod(index) {
				return index + 1
			},
			//页面初始数据获取
			getTableData() {
				const {
					Id: ProjectId
				} = this.project || null
				if (ProjectId != null) {
					this.pagination.tableloading = true
					this.$http.post('PayrollForm/GetPayrollFormAsync', {
						ProjectId,
						PayrollFormType: 1,
						PayrollFormNumber: this.formData.payrollFormNumber==''?null:this.formData.payrollFormNumber,
						Status: this.formData.status,
						CreateDate: (this.formData.createTime == '' || this.formData.createTime == null)?null:this.formData.createTime+'T00:00:00.000Z',
						EndDate: (this.formData.endTime == '' || this.formData.endTime == null)?null:dayjs(this.formData.endTime).endOf('month').format('YYYY-MM-DDT00:00:00.000Z'),
						ConstructionType: this.formData.constructionType == ''? 0 :this.formData.constructionType,
						PersonId: this.formData.personId == ''? 0 :this.formData.personId,
						OrderUserId: this.formData.orderUserId == ''? 0 :this.formData.orderUserId,
						SettlementNumber: this.formData.settlementNumber,
						IsDelete:this.formData.IsDelete,
						pageSize: this.pagination.pagesize,
						pageIndex: this.pagination.currentPage,
					}).then(res => {
						const {
							StatusCode,
							Data,
							TotalCount
						} = res.data || 0
						if (StatusCode == 200) {
							this.payrollList = Data
						} else {
							this.payrollList = []
							this.$message.warning('获取项目收方工资单失败,请重试!')
						}
						this.pagination.total = TotalCount
						this.tableHeightJiSuan()
						this.pagination.tableloading = false
					}).catch(()=>{ this.pagination.tableloading = false })
				} else {
					this.$message.warning('获取项目收方工资单失败!')
				}
			},
			//单数据详情
			getPayrollDetails(row) {
				this.PayrollDetailsEntiy.PayrollDetails = row
				this.PayrollDetailsEntiy.show = true
			},
			//子窗口关闭调用
			childrenCloseEvent() {
				this.PayrollDetailsEntiy.show = false
				this.PayrollDetailsAddEntiy.show = false
				this.getTableData()
			},
			// 获取施工部位
			getConstructionPartEnum() {
				this.$http.post('PayrollForm/GetConstructionPartEnum').then(res => {
					const {
						StatusCode,
						Data
					} = res.data || 0
					if (StatusCode == 200) this.constructionPart = Data
					else this.constructionPart = []
				})
			},
			// 获取施工类别
			getConstructionType() {
				this.$http.post('PayrollForm/GetConstructionType').then(res => {
					const {
						StatusCode,
						Data
					} = res.data || 0
					if (StatusCode == 200) this.constructionType = Data
					else this.constructionType = []
				})
			},
			// 获取工作内容
			getPayrollFormConstructionType() {
				this.$http.post('PayrollForm/GetPayrollFormConstructionType').then(res => {
					const {
						StatusCode,
						Data
					} = res.data || 0
					if (StatusCode == 200) this.payrollFormConstructionType = Data
					else this.payrollFormConstructionType = []
				})
			},
			//获取数据描述
			getDataMessage(type, row) {
				const {
					ConstructionPart,
					ConstructionType,
					JobContent,
					PersonId
				} = row || null
				let messaga = ''
				let Obj
				switch (type) {
					case 'Position':
						Obj = this.constructionPart.find(x => x.Value == ConstructionPart)
						break;
					case 'Category':
						Obj = this.constructionType.find(x => x.Value == ConstructionType)
						break;
					case 'Content':
						Obj = this.payrollFormConstructionType.find(x => x.Value == JobContent)
						break;
					case 'User':
						Obj = this.$store.state.AllUsers.find(x => x.Id == PersonId)
						break;
				}
				if (Obj) {
					if (type != 'User') messaga = Obj.Description
					else messaga = Obj.UserName
				}
				return messaga
			},
			//删除详情
			deletePayrollDetails(row) {
				this.$http.post('PayrollForm/DelPayrollForm', {
					Id: row.Id
				}).then(res => {
					const {
						StatusCode,
						Data
					} = res.data || 0
					if (StatusCode == 200) {
						this.$message.success('删除成功')
					} else {
						this.$message.warning('删除失败,请重试!')
					}
					this.getTableData()
				})
			},
			//导出数据表格
			GetPayrollFormExcel(row) {
				this.$http.post('PayrollForm/GetPayrollFormExcel', {
					id: row.Id
				}).then(res => {
					const {
						StatusCode,
						Data,
						Message
					} = res.data || 0
					if (StatusCode == 200) {
						//文件下载
						publicjs.DownLoadFile({
							...Data
						})
					} else {
						this.$message.warning(Message)
					}
				})
			},
			//下载文件
			DownLoadFileEvent(row) {
				let Data = {
					id: row.id || row.Id,
					FileType: 256,
					Type: 1,
					FileName: '',
				}
				//文件下载
				publicjs.DownLoadFile({
					...Data
				})
			},
			//添加弹框关闭
			payrollFormAddRefEvent() {
				this.$refs.payrollFormAddRef.clearFormData()
			},
			//项目是否完结
			projectOver() {
				const {
					EndDate
				} = this.project || ''
				if (EndDate == undefined || EndDate == '') {
					return false
				} else {
					let chazhi = dayjs(EndDate).diff(Date(), 'day')
					return chazhi < 0 ? true : false
				}
			},
			//时间转化
			shijianzhuanhua(time) {
				if (time == '') return ''
				else return dayjs(time).format('YYYY-MM')
			},
			//表格选择
			tableSelectEvent(values, row) {
				this.tableSelectRows = values
			},
			//时间选择事件
			SettlementNumberEvent(value) {
				if (value == '') return
				this.$http.post('PayrollForm/CheckSettlement', {
					settlementNumber: value,
					projectId: this.project.Id
				}).then(res => {
					this.CheckSettlementResult = res.data
				})
			},
			//修改已经扎帐订单,请谨慎操作
			UpSettlementDialog() {
				if (this.tableSelectRows.length == 0) {
					this.$message.warning('请选择需要年度开账的数据!')
					return
				}
				if (this.tableSelectRows.length > 1) {
					this.$message.warning('年度开账数据只能存在一条!')
					return
				}
				this.kaizhangDialog = {
					show: true,
					SettlementNumber: ''
				}
			},
			//点击开账按钮，打开开账对话框页面
			OpenSettlementDialog(row) {
				this.kaizhangDialog = {
					show: true,
					SettlementNumber: '2025',
					clickrow:row,
				}
			},
			//弹框关闭
			dialogVisibleEvent() {
				this.kaizhangDialog = {
					show: false,
					SettlementNumber: ''
				}
				this.CheckSettlementResult = {
					Message: '',
					StatusCode: 200
				}
			},
			//提交新开账数据
			IsUpSettlementHandler() {
				this.$http.post('PayrollForm/SetSettlement', {
					settlementNumber: this.kaizhangDialog.SettlementNumber,
					orderId: this.tableSelectRows[0].Id,
					projectid:this.tableSelectRows[0].ProjectId
				}).then(res => {
					const {
						StatusCode,
						Data,
						Message
					} = res.data || 0
					if (StatusCode == 200) {
						this.$message.success('年度开账成功!')
						this.dialogVisibleEvent()
						this.getTableData()
					} else {
						this.$message.warning(Message)
					}
				})
			},
			//单独提交新开账数据
			IsUpSettlementHandlerNew() {
				console.log(1234);
				if(this.kaizhangDialog.SettlementNumber==""||this.kaizhangDialog.SettlementNumber==null)
				{
					this.$message.warning('开账年份不能为空，请选择开账年份！')
					return;
				}
				var row=this.kaizhangDialog.clickrow;
				this.$http.post('PayrollForm/SetSettlement', {
					settlementNumber: this.kaizhangDialog.SettlementNumber,
					orderId: row.Id,
					projectid:row.ProjectId
				}).then(res => {
					const {
						StatusCode,
						Data,
						Message
					} = res.data || 0
					if (StatusCode == 200) {
						this.$message.success('年度开账成功!')
						this.dialogVisibleEvent()
						this.getTableData()
					} else {
						this.$message.warning(Message)
					}
				})
			},
			//表格数据合集
			getSummaries(param) {
				const {
					columns,
					data
				} = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '总价';
						return;
					}
					const values = data.map(item => Number(item[column.property]));
					if(index == 7 || index == 9){
						if (!values.every(value => isNaN(value))) {
							sums[index] = values.reduce((prev, curr) => {
								const value = Number(curr);
								if (!isNaN(value)) {
									let sum =  parseFloat(prev)  + parseFloat(curr)
									return sum.toFixed(2);
								} else {
									return prev.toFixed(2);
								}
							}, 0);
							sums[index] += index!=7?' 元':'';
						} else {
							sums[index] = '';
						}						
					}
				});
				return sums;
			},
			//获取用户的信息
			getUserInfo(row, type) {
				let user = this.$store.state.AllUsers.find(u => u.Id == row.UserId) || undefined
				if (user != undefined) return user[type]
				else return ""
			},
			//获取列表中人员
			getPayrollUserAsync(Id) {
				let _this = this
				this.$http.post('PayrollForm/GetPayrollUserAsync', {
					id: Id
				}).then(res => {
					const {
						StatusCode,
						Data
					} = res.data || 0
					if (StatusCode == 200) {
						this.workPersons = Data.map(x=> {
							const { UserId,WorkingDays,Price,TotalPrice } = x || 0
							return { UserId,WorkingDays,Price,TotalPrice }
						})
					}else{
						this.workPersons = []
					}	
				}).catch(()=>{ this.workPersons = [] })
			},
			//表格高度计算
			tableHeightJiSuan(){
				this.tableStyle = document.body.clientHeight - this.$refs.biaotou.clientHeight - 116
			},
		}
	}
</script>

<style scoped>
</style>